# -*- coding: utf-8 -*-
import os
import time,json
from adminApp import create_backgroud_app, db, redis_store
from adminApp.models import Machine, TaskLog,WarnLogs, HardDisk, DefaultNicFlowData as dnf, BandWidthLog,Idc,SourceZabbixSnmpLog, SourceMySnmpLog, SourceAqySnmpLog
from datetime import datetime, timedelta, date
from sqlalchemy import func
from dateutil.relativedelta import relativedelta
from sqlalchemy import or_

# 检测缺少时间点的数据
# 以现有数据检测
if __name__ == "__main__":
    app=create_backgroud_app(os.getenv('FLASK_ENV', 'default'))
    not_finds = []
    success_rs = []

    with app.app_context():
        # 清空表
        # db.session.execute('TRUNCATE TABLE `source_aqy_snmp_log`')
        db.session.execute('TRUNCATE TABLE `source_my_snmp_log`')
        db.session.commit()
        isum = 0
        for root, dirs, files in os.walk('/www/wwwroot/monserver/logs/snmplogs'):
            for f in files:
                print('开始导入：{}'.format(os.path.join(root, f)))
                uuidOrDeviceid=f.split('.')[0]
                # print(uuidOrDeviceid)
                # 查询对应的ID 查询machine
                mid = db.session.query(Machine.id).filter(or_(Machine.system_uuid==uuidOrDeviceid, Machine.aqy_device_id==uuidOrDeviceid)).one_or_none()
                not_finds.append(uuidOrDeviceid)
                if mid:
                    mid = mid[0]
                    # 加载json 文件 插入数据库
                    with open(os.path.join(root, f)) as f:
                        datas = json.load(f)
                        #
                        # 插入爱奇艺
                        # aqy_inserts =[]
                        # for l in datas.get('aqysnmp'):
                        #     # db.session.execute('insert into source_aqy_snmp_log(Unix,BytesSent,OutBytes,machine_id) values("%s","%s","%s","%s")' % (l[0].replace('_',' '),l[1],l[2],mid))
                        #     aqy_inserts.append(dict(Unix=datetime.strptime(l[0], '%Y-%m-%d_%H:%M:%S'),
                        #                             BytesSent=l[1], OutBytes=l[2], machine_id=mid))
                        # db.session.bulk_insert_mappings(SourceAqySnmpLog,aqy_inserts)
                        # db.session.commit()
                        # 插入自己的数据
                        my_inserts = []
                        for l in datas.get('mysnmp'):
                            my_inserts.append(dict(Unix=datetime.strptime(l[0], '%Y-%m-%d_%H:%M:%S'),
                                                   BytesReceive=l[1], OutBytes=l[2],  machine_id=mid))
                        db.session.bulk_insert_mappings(SourceMySnmpLog,my_inserts)
                        db.session.commit()
                        success_rs.append(uuidOrDeviceid)

        print('未导入的文件')
        print(not_finds)
        with open('notputj.json', 'w') as f:
            json.dump(not_finds,f)